from django.db.models import F
from django.shortcuts import render

# Create your views here.
from rest_framework.decorators import action
from rest_framework.viewsets import ModelViewSet,GenericViewSet #GenericViewSet表示可以获取视图集和序列化器的
from rest_framework.mixins import CreateModelMixin,DestroyModelMixin#创建和删除，如果只需要这两部分那么可以只导入这俩部分，如果需要全部，就用ModelVie...
from rest_framework.permissions import IsAuthenticated
from community.models import Article
from .serializers import *
from rest_framework.pagination import PageNumberPagination
from utils.permission import *

class ArticlePageNumberPagination(PageNumberPagination):  #分页
    page_size = 10 #每页10条数据
    page_size_query_param = 'size' #每一页穿参数，通过size去控制每一页的数据
    max_page_size = 100 #最大能展示100条

class ArticleViewSet(ModelViewSet):
    queryset = Article.objects.filter(is_delete=False)#除了逻辑删除，其他的都查看
    serializer_class = ArticleSerializer
    permission_classes = [IsAuthenticated]
    pagination_class = ArticlePageNumberPagination  #分页

    def get_queryset(self):
        if self.action in ['list','retrieve']: #如果你是列表查看或者单条查看，那么只能看已发布的
            return Article.objects.filter(is_delete=False,status=1)
        return self.queryset
    @auto_user
    def create(self, request, *args, **kwargs):
        return ModelViewSet.create(self, request, *args, **kwargs)

    @update_auto_user
    def update(self, request, *args, **kwargs):
        return ModelViewSet.update(self, request, *args, **kwargs)

    @destroy_auto_user
    def destroy(self, request, *args, **kwargs):
        return ModelViewSet.destroy(self, request, *args, **kwargs)

    @action(methods=['get'],detail=False)
    def my(self,request): #查看自己的，未发布和已发布的都可以看
        data = self.get_queryset().filter(user=request.user)
        serializer = self.get_serializer(data,many=True)
        return Response(serializer.data)

    def retrieve(self, request, *args, **kwargs):
        self.get_queryset().filter(id=kwargs['pk']).update(page_view=F('page_view')+1) #查询单条具体的数据，并且每查询一次浏览量也要加1，用 F查询
        return ModelViewSet.retrieve(self, request, *args, **kwargs)

    @action(methods=['get'],detail=True)
    def comment(self,request,pk):
        comments = Comment.objects.filter(article_id=pk,level=1)#先找到不同文章下的评论，文章id=传过来的你点击的文章的id，进行搜索数据，在用序列化器展示
        serializer = CommentSerializer(comments,many=True) #展示
        return Response(serializer.data)

class CommentViewSet(GenericViewSet,CreateModelMixin,DestroyModelMixin):#GenericViewSet这里面有查询集和序列化器(queryset和serialier_class)
    queryset = Comment.objects.filter(is_delete=False,article__status=1) #括号里的后面这个，表示反向查询，未发布的文章不显示，不能进行评论
    serializer_class = CommentSerializer
    permission_classes = [IsAuthenticated]

    #@auto_user #注释是因为测试的时候不好测试
    def create(self, request, *args, **kwargs):
        return CreateModelMixin.create(self, request, *args, **kwargs)

    @destroy_auto_user
    def destroy(self, request, *args, **kwargs):
        return DestroyModelMixin.destroy(self, request, *args, **kwargs)
    
